{% extends '_base_create_update.html' %}

{% block top_css %}
    {{ super() }}

    <!--Treeview-->
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='plugins/bootstrap-treeview/css/bootstrap-treeview.min.css') }}">
    <!--bees-->
    <link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='css/bees.css') }}">

    <style>

        .item .btn.active{
            background-color: #294f75 !important;
            border-color: #25476a  !important;
            color: #fff !important;
        }

        .group {
            padding-top: 16px;
            padding-bottom: 8px;
            border: 1px solid #cccccc6e;
            margin-top: 10px;
            position: relative;
        }


        @media (min-width: 1200px){
            /* 1 4 7 */
            .group:nth-of-type(3n+1) {
                margin-left: 0%;
            }
        }

        .group .tip {
            position: absolute;
            left: -1px;
            top: -13px;
        }

    </style>

{% endblock %}


<!-- Content head -->
{% block head_title %}
    代码发布
{% endblock %}

{% block head_nav %}
    <ol class="breadcrumb">
        <li><a href="#"><i class="fa fa-home"></i></a></li>
        <li><a href="#">代码发布</a></li>
        <li class="active">任务工单</li>
    </ol>
{% endblock %}

<!-- Content body -->
{% block tip %}
    <div class="alert alert-info mar-no">
        <i class="fa fa-circle"></i>&nbsp;&nbsp;请选择需要部署的项目，部署项目会同步到对应环境中的服务器上<b>.</b>
    </div>

    <!-- 加载版本库动画 -->
    <div class="mask"></div>
    <div class="spinner">
        <div class="dot1"></div>
        <div class="dot2"></div>
    </div>
{% endblock %}

{% block body_title %}
    新增任务工单
{% endblock %}

{% block body_form %}
    <div class="panel-body">
        <div class="col-lg-12">
            <div class="panel">
                <div id="bv-wz">
                    <div class="wz-heading pad-top">
                        <!--Nav-->
                        <ul class="row wz-step wz-icon-bw wz-nav-off mar-top wz-steps">
                            <li class="col-xs-6 active bv-tab-error">
                                <a data-toggle="tab" href="#bv-tab1" aria-expanded="true">
                                    <span class="text-danger"><i class="demo-pli-information icon-2x"></i></span>
                                    <p class="text-semibold mar-no">请选择上线项目</p>
                                </a>
                            </li>
                            <li class="col-xs-6">
                                <a data-toggle="tab" href="#bv-tab2">
                                    <span class="text-warning"><i class="demo-pli-male icon-2x"></i></span>
                                    <p class="text-semibold mar-no">请选择项目版本</p>
                                </a>
                            </li>
                        </ul>
                    </div>

                    <!--progress bar-->
                    <div class="progress progress-xs">
                        <div class="progress-bar progress-bar-primary" style="width: 50%; left: 0%; position: relative; transition: all 0.5s ease 0s;"></div>
                    </div>


                    <!--Form-->
                    <form name="taskForm" class="form-horizontal bv-form" novalidate="novalidate"><button type="submit" class="bv-hidden-submit" style="display: none; width: 0px; height: 0px;" disabled="disabled"></button>
                        <div class="panel-body">
                            <div class="tab-content">
                                <!--First tab-->
                                <div id="bv-tab1" class="tab-pane active in">
                                    {% for key, val in data.items() %}
                                    <div class="row">
                                        <p class="bord-btm pad-ver-7 text-main text-bold">{{ val.get('ename') }}</p>
                                        <div class="col-xs-12 mar-btm">
                                            {% for k, v in val.get('child').items() %}
                                                <div class="group col-xs-12 col-lg-3 col-xs-offset-1">
                                                    <div class="tip">
                                                        <label class="label label-pink">{{ v.get('gname') }}</label>
                                                    </div>

                                                    {% for p in v.get('child') %}
                                                        <div class="col-xs-6 item">
                                                            <span data-id="{{ p.pid }}" class="btn btn-default btn-icon">{{ p.pname }}</span>
                                                        </div>
                                                    {% endfor %}
                                                </div>
                                            {% endfor %}
                                        </div>
                                    </div>
                                    {% endfor %}
                                </div>
                                <!--Second tab-->
                                <div id="bv-tab2" class="tab-pane fade">
                                    <div class="row">
                                        <div class="col-lg-12">
                                            <fieldset class="pad-top">
                                                <div class="form-group">
                                                    <label class="col-lg-2 control-label"><span class="text-danger">* </span>上线标题</label>
                                                    <div class="col-lg-8">
                                                        <input type="text" class="form-control" name="title" placeholder="请输入上线标题" autocomplete="off">
                                                    </div>
                                                </div>
                                            </fieldset>
                                        </div>

                                        <div class="col-lg-12 hidden">
                                            <fieldset class="pad-top">
                                                <div class="form-group">
                                                    <label class="col-lg-2 control-label"><span class="text-danger">* </span>工单版本</label>
                                                    <div class="col-lg-8">
                                                        <select class="select2 form-control" name="tag" data-placeholder="请选择工单版本">
                                                            <option value=""></option>
                                                        </select>
                                                    </div>
                                                </div>
                                            </fieldset>
                                        </div>

                                        <div class="col-lg-12 hidden">
                                            <fieldset class="pad-top">
                                                <div class="form-group">
                                                    <label class="col-lg-2 control-label"><span class="text-danger">* </span>工单分支</label>
                                                    <div class="col-lg-8">
                                                        <select class="select2 form-control" name="branch" data-placeholder="请选择工单分支">
                                                            <option value=""></option>
                                                        </select>
                                                    </div>
                                                </div>
                                            </fieldset>
                                        </div>
                                        <div class="col-lg-12 hidden">
                                            <fieldset class="pad-top">
                                                <div class="form-group">
                                                    <label class="col-lg-2 control-label"><span class="text-danger">* </span>分支版本</label>
                                                    <div class="col-lg-8">
                                                        <select class="select2 form-control" name="commit" data-placeholder="请选择分支版本">
                                                            <option value=""></option>
                                                        </select>
                                                    </div>
                                                </div>
                                            </fieldset>
                                        </div>

                                        <div class="col-lg-12">
                                            <fieldset class="pad-top">
                                                <div class="form-group">
                                                    <label class="col-lg-2 control-label"><span class="text-danger">* </span>上线内容</label>
                                                    <div class="col-lg-8">
                                                        <textarea class="form-control" name="content" rows="5" placeholder="请输入上线内容"></textarea>
                                                    </div>
                                                </div>
                                            </fieldset>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <!--Footer button-->
                        <div class="panel-footer text-right">
                            <div class="box-inline">
                                <button type="button" class="previous btn btn-primary disabled">上一步</button>
                                <button type="button" class="next btn btn-primary">下一步</button>
                                <button type="button" class="finish btn btn-primary" disabled="" style="display: none;">完成</button>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
{% endblock %}



{% block buttom_js %}
    {{ super() }}
    <!--bees-->
    <script src="{{ url_for('static', filename='js/bees.js') }}"></script>
    <!--bootstrap-wizard-->
    <script src="{{ url_for('static', filename='plugins/bootstrap-wizard/jquery.bootstrap.wizard.js') }}"></script>
    <!--socket-io-->
    <script type="text/javascript" src="{{ url_for('static', filename='js/socket.io.js') }}"></script>

    <script type="text/javascript">

        $(function () {
            bees.initSelect2({
                width: '100%'
            });

            // 激活项目标签
            $(".item").on('click', 'span', function (e) {
                $(".item").find('.btn').removeClass('active');
                $(this).addClass('active');
            });


            // WEB SOCKET
            // =================================================================
            function fillRevision(project_id, mode) {
                var url = window.location.protocol === "https:" ? "wss://" : "ws://" + document.domain + ':' + location.port;
                var socket = io.connect(url + '/codes');
                socket.on('connect', function () {
                    socket.emit('open', {
                        project_id: project_id
                    });
                });

                socket.on('close', function () {
                    socket.close();
                });

                socket.on('disconnect', function () {
                    socket.close();
                });

                // 服务器端已连接
                socket.on('construct', function () {
                    if(mode=='tag'){
                        showSelectTable('tag');
                        socket.emit('tags');
                    }

                    if(mode=='branch'){
                        showSelectTable('branch');
                        socket.emit('branches');
                    }
                });

                socket.on('tags', function (result) {
                    if(result.event == 'error'){
                        processLoadInfo(false, false);
                    }else {
                        buildTagSelectTable(result.data);
                        processLoadInfo(false, true);
                    }
                    socket.close();
                });

                socket.on('branches', function (result) {
                    if(result.event == 'error'){
                        processLoadInfo(false, false);
                    }else {
                        buildBranchSelectTable(result.data);
                        processLoadInfo(false, true);
                    }
                    socket.close();
                });
            }

            function processLoadInfo(is_show, is_success) {
                if(is_show === true){
                    $(".mask").show();
                    $(".spinner").show();
                    bees.tipInfo({
                        message: '正在加载项目版本信息',
                        timer : 3000
                    })
                }else {
                    $(".mask").hide();
                    $(".spinner").hide();
                    if(is_success === true){
                        bees.tipSuccess({
                            message: '项目版本信息加载成功',
                            timer : 3000
                        })
                    }else {
                        bees.tipError({
                            message: '获取项目版本信息失败',
                            timer : 3000
                        })
                    }

                }
            }

            function showSelectTable(mode){
                if(mode == 'tag'){
                    $('select[name="tag"]').closest('fieldset').parent('div').removeClass('hidden');
                    $('select[name="branch"]').closest('fieldset').parent('div').addClass('hidden');
                    $('select[name="commit"]').closest('fieldset').parent('div').addClass('hidden');
                }else if(mode == 'branch'){
                    $('select[name="tag"]').closest('fieldset').parent('div').addClass('hidden');
                    $('select[name="branch"]').closest('fieldset').parent('div').removeClass('hidden');
                    $('select[name="commit"]').closest('fieldset').parent('div').removeClass('hidden');
                }
            }

            function buildTagSelectTable(data) {
                var options = ['<option value=""></option>'];
                for(var i=0; i<data.length; i++){
                    var option = "<option value="+data[i]+">"+data[i]+"</option>";
                    options.push(option);
                }
                $('select[name="tag"]').empty().append(options);
            }

            var branchData = null;
            function buildBranchSelectTable(data) {
                branchData = data;
                var options = ['<option value=""></option>'];
                for(var branch in branchData){
                    var option = "<option value="+branch+">"+branch+"</option>";
                    options.push(option);
                }
                $('select[name="branch"]').empty().append(options);
            }

            $('select[name="branch"]').on('change', function () {
                var branch = $('select[name="branch"]').val();
                var commitData = branchData[branch];

                var options = ['<option value=""></option>'];
                for(var i=0; i<commitData.length; i++){
                    var option = "<option value="+commitData[i]+">"+commitData[i]+"</option>";
                    options.push(option);
                }
                $('select[name="commit"]').empty().append(options);
            });

            function cleanRevision() {
                $('select[name="tag"]').empty();
                $('select[name="branch"]').empty();
                $('select[name="commit"]').empty();
            }

            // FORM WIZARD
            // =================================================================
            var isValid;
            var project_id;
            var mode;
            $('#bv-wz').bootstrapWizard({
                tabClass		    : 'wz-steps',
                nextSelector	    : '.next',
                previousSelector	: '.previous',
                finishSelector	    : '.finish',
                onTabClick          : function(tab, navigation, index) {
                    return false;
                },
                onInit : function(){
                    $('#bv-wz').find('.finish').hide().prop('disabled', true);
                },
                onTabShow: function(tab, navigation, index) {
                    var $total = navigation.find('li').length;
                    var $current = index+1;
                    var $percent = ($current/$total) * 100;
                    var wdt = 100/$total;
                    var lft = wdt*index;

                    $('#bv-wz').find('.progress-bar').css({width:wdt+'%',left:lft+"%", 'position':'relative', 'transition':'all .5s'});

                    // If it's the last tab then hide the last button and show the finish instead
                    if($current >= $total) {
                        $('#bv-wz').find('.next').hide();
                        $('#bv-wz').find('.finish').show();
                        $('#bv-wz').find('.finish').prop('disabled', false);
                    } else {
                        $('#bv-wz').find('.next').show();
                        $('#bv-wz').find('.finish').hide().prop('disabled', true);
                    }
                },
                onNext: function(){
                    isValid = null;

                    // 需要验证用户是否选择了项目
                    project_id = $(".item").find('.btn.active').data('id');
                    if(!project_id){
                        bees.tipError({
                             message : '请选择需要部署的项目'
                        });
                        isValid =  false;
                    }else {
                        $.getJSON(
                            '{{ url_for("codes.api-project-item", pk=default_pk) }}'.replace(bees.defaultPK, project_id),
                            function (result) {
                                var data = result.data;
                                mode = data.repo_mode;
                                $(".alert").removeClass('show').addClass('hide');
                                processLoadInfo(true, null);
                                cleanRevision();
                                fillRevision(project_id, mode);
                            }
                        )
                    }

                    if(isValid === false) return false;
                },
                onPrevious: function () {
                    $(".alert").removeClass('hide').addClass('show');
                    isValid = null;
                    if(isValid === false) return false;
                },
                onFinish: function () {
                    isValid = null;

                    var eles;
                    if(mode=='tag'){
                        eles = [
                            {
                                name: 'title',
                                ele: $('input[name="title"]'),
                                msg: '上线标题不能为空'
                            },
                            {
                                name: 'tag',
                                ele: $('select[name="tag"]'),
                                msg: '上线版本不能为空'
                            },
                            {
                                name: 'content',
                                ele: $('textarea[name="content"]'),
                                msg: '上线内容不能为空'
                            }
                        ]
                    }else if(mode=='branch'){
                        eles = [
                            {
                                name: 'title',
                                ele: $('input[name="title"]'),
                                msg: '上线标题不能为空'
                            },
                            {
                                name: 'branch',
                                ele: $('select[name="branch"]'),
                                msg: '上线分支不能为空'
                            },
                            {
                                name: 'commit',
                                ele: $('select[name="commit"]'),
                                msg: '分支版本不能为空'
                            },
                            {
                                name: 'content',
                                ele: $('textarea[name="content"]'),
                                msg: '上线内容不能为空'
                            }
                        ]
                    }

                    var formData = {};
                    for(var i=0; i<eles.length; i++){
                        var value = eles[i].ele.val();
                        if(!value){
                            bees.tipError({
                                 message :  eles[i].msg
                            });
                            isValid =  false;
                            break
                        }else {
                            formData[eles[i].name] = value
                        }
                    }
                    formData['project_id'] = project_id;

                    if(isValid === false)return false;

                    setAjaxCSRFToken();
                    $.ajax({
                        type: 'post',
                        url: '{{ url_for("codes.task-create") }}',
                        data :formData,
                        success: function (result) {
                            if (result.code != 200) {
                                $formEle.find('*[name='+ result.data.field +']').focus().addClass('has-error');
                                bees.tipError({
                                    message: result.data.message
                                });
                            }else {
                                bees.tipInfo({
                                    message: '新增成功'
                                });
                                window.location.href = '{{ url_for("codes.task-list") }}'
                            }
                        }
                    });
                }
            });
        });
    </script>

{% endblock %}
